<?php
/**
 * User: hjd-yao
 * Date: 2019/6/11
 * Time: 18:57
 */

namespace DC\BonusCenter\Services;


use App\Models\Bonus\BonusPoolsModel;
use App\Models\Bonus\BonusRecordModel;
use App\Models\PlatFinanceModel;
use App\Models\Rule\BonusRuleModel;
use App\Models\Shop\UserAchievementModel;
use App\Models\User\AccountFlowModel;
use Carbon\Carbon;
use DC\BonusCenter\CommonBonus;
use DC\UserCenter\Models\UserBaseModel;
use DC\UserCenter\Models\UserWalletModel;
use Illuminate\Support\Facades\DB;

class RegBonus extends CommonBonus
{
    private $billMoney ;

    public function award($new_uid)
    {
        $user_info = UserBaseModel::init()->find($new_uid);
        $this->billMoney = self::BillMoney($new_uid);
        $this->activeSelf($new_uid);
        if($user_info->active_type == 1){
            $this->achievement($new_uid,$this->billMoney);
            //实单激活-升级
            $this->uplevel($new_uid);
            $this->money_tj($new_uid,$this->billMoney,1);
            $this->money_bd($new_uid,$this->billMoney);
//            $this->bonusSelf($new_uid,$this->billMoney);
//            $this->bonusShare($new_uid,$this->billMoney);
//            $this->AgentUpgrade($new_uid);
//            $this->BonusRange($new_uid,$this->billMoney);
//            $this->EntryCenterBonus($new_uid,$this->billMoney);
//            $this->AddPrizePool($this->billMoney);

            PlatFinanceModel::init()->incomeFinance($this->billMoney);
        }else{
            $this->achievement($new_uid,0);
        }

    }

    /**
     * 管理奖
     * @param $tj_uid
     * @param $base_money
     */
    public function money_gl($tj_uid,$base_money){
        $bc_gl=BonusRuleModel::where('name','guanli')->first();
        $gl_ratio=$bc_gl->rule1*0.01;
        $gl_min=$bc_gl->rule2;

        $target = UserBaseModel::init()->find($tj_uid);
        if(!$target || !$target->referrer_id || $base_money <= 0){
            return false ;
        }
        $t_ids = UserBaseModel::where('status', '>', 0)
            ->whereRaw("FIND_IN_SET(`member_id`,?)", [$target->referrer_ids])
            ->orderBy('tdeep', 'desc')->pluck('member_id')->toArray();

        if (!$t_ids) {
            return false;
        }
        foreach ($t_ids as $tid){
            $hj_money=$base_money*$gl_ratio;
            if($gl_min>$hj_money){
                break;
            }
            $t_info = UserBaseModel::find($tid);
            if (!$t_info) {
                break;
            }
            //在判断用户级别前重置$base_money.表示该金额奖项有只是没给这个人发
            $base_money=$hj_money;
            if(($t_info->status!=1)||($t_info->level!=1)){
                continue;
            }
            if($hj_money > 0){
                $this->setBonusAllot()->settleBonus(43,$tid,$tj_uid,$hj_money,2);
            }
            unset($hj_money,$t_info);
        }
        return true ;
    }
    /**
     * 报单奖
     */
    public function money_bd($new_uid,$yeji){
        $bc_bd=BonusRuleModel::where('name','baodan')->first();
        $bd_ratio=$bc_bd->rule1*0.01;
        $hj_money=$yeji*$bd_ratio;
        $user=UserBaseModel::where('member_id',$new_uid)->first();
        if($user->bd_uid==0){
            return false;
        }
        $bd_info = UserBaseModel::find($user->bd_uid);
        if(!$bd_info){
            return false;
        }
        if(($bd_info->status!=1)||($bd_info->level!=1)){
            return false;
        }
        if($hj_money > 0){
            $this->setBonusAllot()->settleBonus(45,$user->bd_uid,$new_uid,$hj_money,2);
        }
    }
    /**
     * 推荐奖
     */
    public function money_tj($new_uid,$yeji,$type){
        $bc_tj=BonusRuleModel::where('name','tuijian')->first();
        if($type==1){
            $tj_ratio=$bc_tj->rule1*0.01;
        }elseif($type==2){
            $tj_ratio=$bc_tj->rule2*0.01;
        }elseif($type==3){
            $tj_ratio=$bc_tj->rule3*0.01;
        }
        $hj_money=$yeji*$tj_ratio;
        $user=UserBaseModel::where('member_id',$new_uid)->first();
        if($user->referrer_id==0){
            return false;
        }
        $tj_info = UserBaseModel::find($user->referrer_id);
        if(!$tj_info){
            return false;
        }
        if(($tj_info->status!=1)||($tj_info->level!=1)){
            return false;
        }
        if($hj_money > 0){
            $this->setBonusAllot()->settleBonus(42,$user->referrer_id,$new_uid,$hj_money,2);
            //管理奖
            $this->money_gl($user->referrer_id,$hj_money);
        }
    }

    /**
     * 升级
     * @param $new_uid
     */
    public function uplevel($new_uid){
        $user=UserBaseModel::where('member_id',$new_uid)->first();
        $user->level=1;
        $user->save();
        return true;
    }

    // 获取激活时 报单金额
    public function BillMoney($new_uid){
      $bc_reg=BonusRuleModel::where('name','reg')->first();
      $bill_money=$bc_reg->rule1;
      return $bill_money ;
    }

    // 激活自己 更该自己的 报单金额 如果是 合伙人 更新V4
    private function activeSelf($new_uid){
        $user_info = UserBaseModel::init()->find($new_uid);
        $user_info->bill_money = $this->billMoney;
        $user_info->left_bill = $this->billMoney ;
        if ($user_info->is_partner == 1 && $user_info->reg_type < 4) {
            $user_info->reg_type = 4 ;
        }
        if($user_info->save()){
            return false ;
        }
        return true ;
    }
    // 这一步 添加 直推人数 和 团队人数
    public function achievement($new_uid,$money){

        $user_info = UserBaseModel::init()->find($new_uid);

        if(!$user_info || $user_info->status == 0 || $user_info->referrer_id == 0){
            return false;
        }

        $referrer_data['share_num'] = DB::raw('`share_num`+1' );
        UserBaseModel::where('status','>=',0)->where('member_id', $user_info->referrer_id)->update($referrer_data);

        $userAct = new UserAchievementModel() ;
        $userAct ->addUserAcInfo($user_info->referrer_id,1,0,$money,0,0);

        $referrer_ids = array_reverse(str2arr($user_info->referrer_ids));

        $team_data['share_team_num'] = DB::raw('`share_team_num`+1');
        $team_data['left_bill'] = DB::raw('`left_bill`+'.$money);

        UserBaseModel::where('status','>',0)->whereIn('member_id', $referrer_ids)->update($team_data);

        $this->addUserAcInfo($new_uid,$money);

        return true ;
    }


    public function UpLevelAchievement($new_uid,$money){

        $user_info = UserBaseModel::init()->find($new_uid);

        if(!$user_info || $user_info->status == 0 || $user_info->referrer_id == 0){
            return false;
        }

        $userAct = new UserAchievementModel() ;
        $userAct ->addUserAcInfo($user_info->referrer_id,1,0,$money,0,0);

        $referrer_ids = array_reverse(str2arr($user_info->referrer_ids));

        $team_data['left_bill'] = DB::raw('`left_bill`+'.$money);

        UserBaseModel::where('status','>',0)->whereIn('member_id', $referrer_ids)->update($team_data);

        $this->addUserAcInfo($new_uid,$money);

        $this->bonusSelf($new_uid,$money,59);
        $this->bonusShare($new_uid,$money);
        $this->AgentUpgrade($new_uid);
        $this->BonusRange($new_uid,$money);
        $this->EntryCenterBonus($new_uid,$money);
        $this->AddPrizePool($money);
        PlatFinanceModel::init()->incomeFinance($money);

        return true ;
    }


    // 添加 每日 業績統計
    public function addUserAcInfo($new_uid,$money){
        $user_info = UserBaseModel::init()->find($new_uid);
        $referrer_ids = array_reverse(str2arr($user_info->referrer_ids));
        $userAct = new UserAchievementModel() ;
        foreach ($referrer_ids as $referrer_id){
            $min_bill = 0 ;
            // 判断 新增业绩 是否 在我小区
            $flag = false;
            $flag = $this->check_is_min_zone($new_uid,$referrer_id);
            if($flag){
                $min_bill = $money ;
            }
            // 添加 每日 新增业绩
            $userAct ->addUserAcInfo($referrer_id,0,1,0,$money,$min_bill);
            unset($referrer_id);
        }
        return true ;
    }

    public function check_is_min_zone($new_uid,$target_id){
        $user_info = UserBaseModel::init()->find($new_uid);
        $referrer_ids = array_reverse(str2arr($user_info->referrer_ids));
        array_push($referrer_ids,$new_uid);
        $max_bill = UserBaseModel::where('status','>',0)->where('referrer_id',$target_id)->max('left_bill');
        $max_member_id =  UserBaseModel::where('status','>',0)->where('referrer_id',$target_id)->where('left_bill',$max_bill)->orderBy('member_id','asc')->value('member_id');
        if(!$max_member_id){
            return false ;
        }
        if(in_array($max_member_id,$referrer_ids)){
            return false ;
        }
        return true ;
    }


    // 报单激活 赠送 等值 报单积分
    private function bonusSelf($new_uid,$money,$change_type=58)
    {
        $bonus = $money;
        if(!$bonus||$bonus<=0){
            return false;
        }
        $field = 'money1';
        $before_money = UserWalletModel::where('member_id',$new_uid)->value($field);
        UserWalletModel::where('member_id',$new_uid)->increment($field,$bonus);
        AccountFlowModel::init()->createFlow($new_uid,$bonus,1,[
            'before_money'=>$before_money,
            'change_type'=>$change_type,
            'relate_uid'=>$new_uid,
            'money_type'=>1,
        ]);
        return true ;
    }

    // 检测 封顶 计算 实际奖金
    private function CheckBonusMax($target_uid,$bonus_max,$bonus_money,$change_type){
        $return_bonus = 0;
        if ($bonus_max <= 0) {
            $return_bonus = $bonus_money;
        }else{
            $bonus_real = BonusRecordModel::init()->where('target_uid', $target_uid)->where('bonus_type', $change_type)->sum('fact_bonus') ?? 0;
            if ($bonus_real >= $bonus_max) {
                $return_bonus = 0;
            } else {
                if ($bonus_real + $bonus_money >= $bonus_max) {
                    $return_bonus = $bonus_max - $bonus_real;
                } else {
                    $return_bonus = $bonus_money;
                }
            }
        }
        return $return_bonus;
    }

    // 直接 分享将
    public function bonusShare($new_uid,$money)
    {
        $info = UserBaseModel::init()->find($new_uid);
        if(!$info || $info->status !=1 || $info->referrer_id == 0){
            return false;
        }

        $target_info = UserBaseModel::init()->find($info->referrer_id);

        if(!$target_info){
            return false ;
        }
        $bonus = 0 ;
        if($target_info->level == 1){
            $bonus_rate = get_rule('share_direct_give_score1');
            $bonus_max =  get_rule('share_direct_give_score1_max') ?? 0;
            $bonus_money = $money * $bonus_rate * 0.01 ;
            if($bonus_money >= $bonus_max){
                $bonus = $bonus_max ;
            }
        }else{
            $bonus_rate = get_rule('share_direct_give_score2');
            $bonus = $money * $bonus_rate * 0.01 ;
        }

        if($bonus > 0 && $target_info->status == 1){
            $this->setBonusAllot()->settleBonus(42,$info->referrer_id,$new_uid,$bonus,2);
        }

        if($target_info->referrer_id){
            $this->bonusTwoDirect($target_info->referrer_id,$new_uid,$money);
        }
        return true ;
    }

    // 间接分享将
    private function bonusTwoDirect($target_uid,$relate_uid,$money)
    {

        $target = UserBaseModel::init()->find($target_uid);
        $bonus_rate = get_rule('share_between_give_score');
        $bonus = $money * $bonus_rate * 0.01 ;

        if($bonus > 0 && $target->status == 1){
            $this->setBonusAllot()->settleBonus(43,$target_uid,$relate_uid,$bonus,2);
        }

        $this->BonusRecovery($target_uid,$relate_uid,$bonus);
        return true ;
    }

    // 回本奖
    private function BonusRecovery($target_uid,$relate_uid,$money){
        $target = UserBaseModel::init()->find($target_uid);
        if(!$target || !$target->referrer_id || $money <= 0){
            return false ;
        }

        $t_ids = UserBaseModel::where('status', '>', 0)
            ->whereRaw("FIND_IN_SET(`member_id`,?)", [$target->referrer_ids])
            ->orderBy('tdeep', 'desc')->pluck('member_id')->toArray();

        if (!$t_ids) {
            return false;
        }

        $bonus_rate = get_rule('share_return_give_score');

        foreach ($t_ids as $tid) {

            $t_info = UserBaseModel::find($tid);

            if (!$t_info) {
                continue;
            }

            $bonus = $money * $bonus_rate * 0.01 ;

            if ($bonus >=1 && is_numeric($bonus) && $t_info->status==1) {
                $this->setBonusAllot()->settleBonus(44, $tid, $relate_uid, $bonus, 2);
            }
            $money = $bonus;

            unset($bonus,$t_info);
        }

        return true ;
    }

    // 管理獎升級 規則
    public function AgentUpgrade($uid){

        $user_info = UserBaseModel::init()->find($uid);

        if(!$user_info || $user_info->status == 0 || !$user_info->referrer_id ){
            return false;
        }

        $t_ids = UserBaseModel::where('status','>',0)->whereRaw("FIND_IN_SET(`member_id`,?)",[$user_info->referrer_ids])->orderBy('tdeep','desc')->pluck('member_id');

        if(!$t_ids){
            return false;
        }

        foreach ($t_ids as $tid){
            $this->EachAgentUpgrade($tid);
        }

    }

    private function EachAgentUpgrade($target_uid){

        $target =  UserBaseModel::init()->find($target_uid);

        $bonus_rule = format_rule(json_decode(get_rule('management_condition'),true));

        if(!$bonus_rule){
            return false;
        }

        $count = count($bonus_rule);

        if($target['reg_type'] >= $count){
            return false ;
        }

        $flag = false ;

        $next_level = $target['reg_type'] +1;
        $condition1 = $bonus_rule[$next_level][1];  // 小市場業績
        $condition2 = $bonus_rule[$next_level][2];  // 直推人數

        if($target['reg_type'] >= 0 && $target['reg_type'] < 4 ){
            $num1 =  $this->getMineZoneAct($target_uid); // 獲取最小區業績
            $num2 = $target->share_num ?? 0;

            if($num1 >=($condition1 * 10000) && $num2 >=$condition2){
                $flag = true;
            }
        }elseif($target['reg_type'] >= 0 && $target['reg_type'] < $count){

            $num1 = $this->getMineZoneAct($target_uid);  // 小市場業績
            $num2 = $target->share_num ?? 0;             // 直推人數

            $condition3 =  $bonus_rule[$next_level][3]; //  傘下 綫數

            $condition4 =  $bonus_rule[$next_level][4]; // 需求 級別

            $condition5 = 0;
            $rec_infos =  UserBaseModel::where('referrer_id',$target_uid)->where('status','>=',0)->get();
            foreach ($rec_infos as $rec_info){
                $condition6 = 0;
                $condition6 = UserBaseModel::where('reg_type','>=',$condition4)->whereRaw("FIND_IN_SET(?,referrer_ids)",$rec_info->member_id)->count() ?? 0;
                if($condition6 >0 || $rec_info->reg_type >= $condition4){
                    $condition5 ++ ;
                }
                unset($condition6,$rec_info);
            }

            if($num1 >= ($condition1 * 10000) && $num2 >=$condition2 && $condition5 >= $condition3){
                $flag = true;
            }

        }else{
            return false ;
        }

        if($flag){
            if($next_level > 0 && $next_level >$target['reg_type'] ){
                UserBaseModel::where('member_id',$target_uid)->update(['reg_type'=>$next_level]);
                return true ;
            }
        }
        return false ;
    }

    // 獲取最小區業績
    private function getMineZoneAct($uid){
        $user_info  =  UserBaseModel::init()->find($uid);

        $min_bill = 0 ;
        $max_bill = UserBaseModel::where('status','>',0)->where('referrer_id',$uid)->max('left_bill');

        $total_bill =  UserBaseModel::where('status','>',0)->where('referrer_id',$uid)->sum('left_bill') ;

        $min_bill = $total_bill - $max_bill ;

        return $min_bill ;
    }


   // 管理 极差奖
    public function BonusRange($uid,$money)
    {
        $info = UserBaseModel::init()->find($uid);

        if(!$info || !$info->referrer_id || $info->status == 0){
            return false;
        }

        $t_ids = UserBaseModel::init()->where('status', '>', 0)
            ->whereRaw("FIND_IN_SET(`member_id`,?)", [$info->referrer_ids])
            ->where('level', '>',1)->where('reg_type', '>',0)->orderBy('tdeep', 'desc')->pluck('member_id')->toArray();

        if (!$t_ids) {
            return false;
        }

        $start_rate = 0;
        $start_agent = 0;
        $range_num = [
            '1' => ['num' => 0],
            '2' => ['num' => 0],
            '3' => ['num' => 0],
            '4' => ['num' => 0],
            '5' => ['num' => 0],
            '6' => ['num' => 0],
            '7' => ['num' => 0],
            '8' => ['num' => 0],
        ];;

        $bonus_rule = format_rule(json_decode(get_rule('management_award'),true));

        if(!$bonus_rule){
            return false;
        }

        foreach ($t_ids as $tid) {

            $t_info = UserBaseModel::init()->find($tid);

            if (!$t_info) {
                continue;
            }

            $reg_type = $t_info->reg_type;

            if ($reg_type == $start_agent) {
                if($reg_type != 4){
                    if ($range_num[$reg_type]['num'] < 2) {
                        $range_num[$reg_type]['num']++;
                        $this->BonusEquallyLevel($tid, $uid,$reg_type,$range_num[$reg_type]['num'],$money);
                    }
                }else{
                    if ($range_num[$reg_type]['num'] < 1) {
                        if($t_info->is_partner == 1){
                            $range_num[$reg_type]['num']++;
                            $this->BonusEquallyLevel($tid, $uid,$reg_type,$range_num[$reg_type]['num'],$money);
                        }
                    }
                }
                continue;
            } else {
                if (isset($bonus_rule[$reg_type]) && $reg_type > $start_agent) {

                    $bonus_rate = $bonus_rule[$reg_type][1] ?? 0;
                    $bonus = ($bonus_rate - $start_rate) * $money * 0.01;

                    if ($bonus >0 && is_numeric($bonus) && $t_info->status == 1 && $t_info->level > 1) {
                        $this->setBonusAllot()->settleBonus(46, $tid, $uid, $bonus, 2);
                    }
                    unset($bonus);
                    $start_rate = $bonus_rate;
                    $start_agent = $reg_type;
                }
            }
            unset($reg_type, $bonus_rate, $t_info);
        }

        return true;
    }
    // 平级奖
    private function BonusEquallyLevel($target_uid,$relate_uid,$reg_type,$t_deep,$money){

        $target = UserBaseModel::init()->find($target_uid);
        if($target->is_partner == 1 && $reg_type == 4 && $t_deep == 1){
           $bonus_rate = get_rule('flat_level_award_given') ?? 0 ;
        }else{
            $bonus_rule =  format_rule(json_decode(get_rule('flat_level_award'),true));

            $bonus_rate = $bonus_rule[$reg_type][$t_deep] ?? 0;
        }
        $bonus =  $money * $bonus_rate * 0.01 ;

        if($bonus >0 &&is_numeric($bonus) && $target->status == 1 && $target->level > 1){
            $this->setBonusAllot()->settleBonus(47,$target_uid,$relate_uid,$bonus,2);
        }
        return true ;
    }


    // 运营中心

    public function EntryCenterBonus($new_uid,$money){
        $user_info = UserBaseModel::init()->find($new_uid);
        if(!$user_info || !$user_info->referrer_id || $user_info->status == 0){
            return false;
        }

        $t_info = UserBaseModel::init()->where('status', '>', 0)
            ->whereRaw("FIND_IN_SET(`member_id`,?)", [$user_info->referrer_ids])
            ->where('is_bill',1)->orderBy('tdeep', 'desc')->first();

        if(!$t_info){
            return false ;
        }

        $bonus_rate = get_rule('declaration_award') ?? 0 ;
        $bonus = $money * $bonus_rate * 0.01 ;

        if($bonus >0 &&is_numeric($bonus) && $t_info->status == 1){
            $this->setBonusAllot()->settleBonus(49,$t_info->member_id,$new_uid,$bonus,2);
        }
        return true ;

    }

    // 新增业绩 添加各种奖金池
    public function AddPrizePool($money){

        $bonus_pools = new BonusPoolsModel() ;

        // 全球分紅
        $bonus_rate1 = get_rule('global_partnership') ?? 0;
        $bonus1 = $money * $bonus_rate1 * 0.01 ;
        if($bonus1 > 0 && is_numeric($bonus1)){
            $bonus_pools->incomeFinance($bonus1,1);
        }
        // 股東分紅
        $bonus_rate2 = get_rule('shareholder_award') ?? 0;
        $bonus2 = $money * $bonus_rate2 * 0.01 ;
        if($bonus2 > 0 && is_numeric($bonus2)){
            $bonus_pools->incomeFinance($bonus2,2);
        }

        // 福利分紅
        $bonus_rate3 = get_rule('welfare_award') ?? 0;
        $bonus3 = $money * $bonus_rate3 * 0.01 ;
        if($bonus3 > 0 && is_numeric($bonus3)){
            $bonus_pools->incomeFinance($bonus3,3);
        }

        // 合夥人分紅
        $bonus_rate4 = get_rule('partner_award') ?? 0;
        $bonus4 = $money * $bonus_rate4 * 0.01 ;
        if($bonus4 > 0 && is_numeric($bonus4)){
            $bonus_pools->incomeFinance($bonus4,4);
        }

        return true ;
    }


    // 合伙人分红
    public function bonusMonthAward($money){

        if (!$money || $money <=0) {
            return false;
        }

        $member_ids = UserBaseModel::where('is_partner', 1)->orderBy('member_id', 'desc')->pluck('member_id')->toArray();

        if (!$member_ids || count($member_ids) <= 0) {
            return false;
        }

        $sys_partner_num = get_rule('partner_num') ;
        $partner_award_rate = get_rule('partner_award_rate') ?? 100;

        $bonus = $money * $partner_award_rate * 0.01 ;

        $each_bonus = round($bonus / $sys_partner_num, 2) ?? 0;

        if (!$each_bonus) {
            return false;
        }

        foreach ($member_ids as $tid) {
            $t_info = UserBaseModel::init()->find($tid);
            if (!$t_info) {
                return false ;
            }
            if ($each_bonus >0 && is_numeric($each_bonus) && $t_info->status == 1) {
                $this->setBonusAllot()->settleBonus(50, $tid, 0, $each_bonus, 2);
            }
            unset($t_info);
        }
        BonusPoolsModel::init()->expendFinance($money,4);
        return true ;
    }


    // 股东分红

    public function bonusShareholderAward($type='test'){

        $model = new BonusPoolsModel();
        // 本周开始
        $start_week = Carbon::now()->startOfWeek()->timestamp;

        // 测试 走这一判断
        if ($type == 'test') {
            // 本周结束
            $last_start_week = Carbon::now()->endOfWeek()->timestamp;
            $money = $model::where('change_type', 2)->whereBetween('date', [$start_week, $last_start_week])->sum('income') ?? 0;
        } else {
            // 上周开始
            $last_start_week = Carbon::now()->subWeek()->startOfWeek()->timestamp;
            $money = $model::where('change_type', 2)->whereBetween('date', [$last_start_week, $start_week])->sum('income') ?? 0;
        }

        if ($money <= 0) {
            return false;
        }

        $member_ids = UserBaseModel::init()->where('reg_type', '>=', 8)->orderBy('member_id', 'desc')->pluck('member_id')->toArray();

        if (!$member_ids || count($member_ids) == 0) {
            return false;
        }

        $shareholder_award_rate = get_rule('shareholder_award_rate') ?? 100;

        $bonus = $money * $shareholder_award_rate * 0.01;

        $each_bonus = round($bonus / count($member_ids), 2) ?? 0;

        if (!$each_bonus || $money <= 0) {
            return false;
        }

        foreach ($member_ids as $tid) {
            $t_info = UserBaseModel::init()->find($tid);
            if (!$t_info) {
                return false;
            }
            if ($each_bonus > 0 && is_numeric($each_bonus) && $t_info->status == 1) {
                $this->setBonusAllot()->settleBonus(48, $tid, 0, $each_bonus, 2);
            }
            BonusPoolsModel::init()->expendFinance($bonus, 2);
            unset($t_info);
        }
        return true;
    }

   // 全球分红
    public function global_partnership($type='test'){

        $member_ids = UserBaseModel::init()->where('status', 1)->orderBy('member_id', 'desc')->pluck('member_id')->toArray();

        if(!$member_ids || count($member_ids) == 0){
            return false ;
        }

        $count = 0 ;
        $list = [] ;
        foreach ($member_ids as $tid){
            $data = $this->each_global_partnership_level($tid);
            if(isset($data) && $data['num'] > 0){
                $count += $data['num'] ;
                $list[] = $data;
            }
            unset($tid,$data);
            continue ;
        }


        if(empty($list) || $count <= 0 ){
            return false ;
        }

        $model = new BonusPoolsModel();
        // 本周开始
        $start_week = Carbon::now()->startOfWeek()->timestamp;

        // 测试 走这一判断
        if ($type == 'test') {
            // 本周结束
            $last_start_week = Carbon::now()->endOfWeek()->timestamp;
            $money = $model::where('change_type', 1)->whereBetween('date', [$start_week, $last_start_week])->sum('income') ?? 0;
        } else {
            // 上周开始
            $last_start_week = Carbon::now()->subWeek()->startOfWeek()->timestamp;
            $money = $model::where('change_type', 1)->whereBetween('date', [$last_start_week, $start_week])->sum('income') ?? 0;
        }


        if($money <=0){
            return false ;
        }

        $global_partnership_rate = get_rule('global_partnership_rate') ?? 100;

        $bonus_total = $money * $global_partnership_rate * 0.01 ;

        $each_bonus = round($bonus_total / $count, 2) ?? 0;


        if (!$each_bonus || $money <=0) {
            return false;
        }

        foreach ($list as $key=>$item){
            $this->do_each_global_partnership($item,$each_bonus);
        }
        BonusPoolsModel::init()->expendFinance($bonus_total,1);
        return true ;
    }

    public function do_each_global_partnership($data,$each_bonus){


        $target_id = $data['uid'];
        $bonus_num = $data['num'] ;
        $bonus_money = $each_bonus * $bonus_num ;
        if($bonus_money >= $data['bonus_money']){
            $bonus_money = $data['bonus_money'] ;
        }
        $bonus = $this->CheckBonusMax($target_id,$data['bonus_max'],$bonus_money,45);
        if($bonus >0 && is_numeric($bonus)){
            $this->setBonusAllot()->settleBonus(45, $target_id, 0, $bonus, 2);
        }
        return true ;
    }

    public function each_global_partnership_level($uid){

        $user_info = UserBaseModel::init()->find($uid);
        if(!$user_info){
            return false ;
        }

        $min_bill = $this->getMineZoneAct($user_info->member_id);

        $bonus_rule_condition1 =  format_rule(json_decode(get_rule('global_partnership_condition1'),true));

        $bonus_rule_min_bill = $bonus_rule_condition1[1][1] * 10000 ;

        if($min_bill < $bonus_rule_min_bill){
            return false ;
        }



        // 获取奖励等级
        $bonus_level = 0 ;
        foreach ($bonus_rule_condition1 as $key=>$value){
            if($min_bill >= ($value[1] * 10000)){
                $bonus_level = $key ;
                continue ;
            }
        }

        if($bonus_level == 0){
            return false ;
        }

        // 根据奖励等级 判断 是否 满足 发奖条件

        $flag = false ;
        $flag = $this->check_is_give_global_partnership($uid,$bonus_level);

        if(!$flag){
            return false ;
        }

        // 判断 当前 等级 的奖励 和是否 封顶

        $global_partnership_award =  format_rule(json_decode(get_rule('global_partnership_award'),true));

        if(!$global_partnership_award || !isset($global_partnership_award[$bonus_level])){
            return false;
        }

        $bonus_max = $global_partnership_award[$bonus_level][1] * 10000;
        $bonus_money = $global_partnership_award[$bonus_level][2] ;

        $num = $bonus_money / 100 ;

        return ['num'=>$num,'bonus_money'=>$bonus_money,'bonus_max'=>$bonus_max,'uid'=>$uid] ;
    }

    // 判断 是否 满足 全球分红奖 条件
    public function check_is_give_global_partnership($uid,$bonus_level){

        $user_info = UserBaseModel::init()->find($uid);

        $bonus_rule_condition2 =  format_rule(json_decode(get_rule('global_partnership_condition2'),true));

        if(!$bonus_rule_condition2){
            return false ;
        }
        $bonus_rule = $bonus_rule_condition2[$bonus_level] ;
        if(!$bonus_rule){
            return false ;
        }


        $condition1 = $bonus_rule[1] ; // 时间 几个月

        $begin_time = Carbon::now()->subMonth($condition1)->endOfMonth()->timestamp;
        $end_time=Carbon::now()->timestamp;



        $condition2 = $bonus_rule[2] * 10000 ; // 需求业绩

        $condition3 = $bonus_rule[3] ;  // 需求等级

        $self_bill = UserAchievementModel::init()->where('user_id',$uid)->whereBetween('created_at',[$begin_time,$end_time])->sum('team_min_achievement') ?? 0;

        if($self_bill >= $condition2 && $user_info->level >= $condition3){
            return true ;
        }
        return false ;
    }

}